package com.pansoft.openplanet.util;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import androidx.appcompat.app.AlertDialog;

import com.efounder.chat.model.LogoutEvent;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.FileDeleteUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.constant.TalkChainConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.utilcode.util.ActivityUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;

import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.utilcode.util.ActivityUtils.startActivity;

/**
 * 对比本地与服务器的信息
 */
public class AssetsCompareLocalWithServerManager {
    private static final String TAG = "CompareLocalWithServer";
    private Context mContext;

    public AssetsCompareLocalWithServerManager(Context mContext) {
        this.mContext = mContext;
    }

    public void startCompare() {
        getEthUserInfo();
    }


    private void getEthUserInfo() {
        HashMap<String, String> map = new HashMap<>();
        map.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
        TCRequestUtil.getOAuthRequest(TAG, "oauth/userInfo", map, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    if ("{}".equals(response)) {
                        //showLogOutAlert("用户不存在，请重新登录");
                        EnvironmentVariable.setProperty("tc_ethAddress", "");
                        EnvironmentVariable.setProperty("tc_ethPublicKey", "");
                        EventBus.getDefault().post(new LogoutEvent(LogoutEvent.TYPE_LOGIN_OUT_OF_DATE));
                        return;
                    }
                    JSONObject userObject = new JSONObject(response);
                    if (userObject.has("userInfo")) {
                        JSONObject user = userObject.getJSONObject("userInfo");
                        EnvironmentVariable.setUserID(String.valueOf(user.getInt("imUserId")));
                        EnvironmentVariable.setProperty(CHAT_USER_ID, String.valueOf(user.getInt("imUserId")));
                        EnvironmentVariable.setProperty(CHAT_PASSWORD, user.getString("imPassword"));

                        //保存服务器获取的ethAddress
                        String serverEthAddress = user.optString("ethAddress", "");
                        if (!serverEthAddress.toLowerCase().startsWith("0x") && !serverEthAddress.equals("")) {
                            serverEthAddress = "0x" + serverEthAddress;
                        }
                        //星球
                        EnvironmentVariable.setProperty("tc_planet", user.optString("planet", ""));
                        //用户信息json
                        EnvironmentVariable.setProperty("tc_user_info", user.toString());

                        //1.比对主钱包地址
                        if (!compareEthAddress(serverEthAddress)) {
                            //对比不一致
                            return;
                        }
                        //2.比对通讯私钥公钥
                        compareCommunicationKey();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {
                if (error != null && error.equals("TokenExpireLogOut")) {
                    //showLogOutAlert("用户登录过期，请重新登录");
                    EnvironmentVariable.setProperty("tc_ethAddress", "");
                    EnvironmentVariable.setProperty("tc_ethPublicKey", "");
                    EventBus.getDefault().post(new LogoutEvent(LogoutEvent.TYPE_LOGIN_OUT_OF_DATE));
                }
            }
        });
    }


    /**
     * 对比本地与服务器的 主钱包地址
     *
     * @param serverEthAddress
     */
    private boolean compareEthAddress(String serverEthAddress) {
        String localEthAddress = EnvironmentVariable.getProperty("tc_ethAddress", "");
        if (!serverEthAddress.toLowerCase().equalsIgnoreCase(localEthAddress)) {
            //本地与服务器不一致
            showDisCordDialog();
            return false;
        }
        EnvironmentVariable.setProperty("tc_ethAddress", serverEthAddress);
        return true;
    }

    // 比对通讯私钥公钥
    private void compareCommunicationKey() {
        TCAccountManager openAccountManager = new TCAccountManager(mContext);
        openAccountManager.checkAndUpdateMessageKey(EnvironmentVariable.getProperty(CHAT_USER_ID, "")
                , false, new TCAccountManager.AccountManagerListener() {
                    @Override
                    public void onSuccess(Object object) {

                    }

                    @Override
                    public void onFail(String fail) {

                    }
                });
    }


    /**
     * 显示不一致的对话框
     */
    private void showDisCordDialog() {
        new AlertDialog.Builder(ActivityUtils.getTopActivity())
                .setTitle(ResStringUtil.getString(R.string.common_text_hint))
                .setCancelable(false)
                .setMessage(ResStringUtil.getString(R.string.guide_dialog__check_baseid_error_hint))
                .setPositiveButton(ResStringUtil.getString(R.string.common_text_confirm), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                        new AccountDao(mContext).deleteByCurentImuserId();
                        File dirFile = new File(TalkChainConstant
                                .getDataFilePath(mContext) + File.separator + EnvironmentVariable.getUserName());
                        FileDeleteUtil.delete(dirFile);
                        EnvironmentVariable.setProperty(CHAT_USER_ID, "");
                        EnvironmentVariable.setProperty(CHAT_PASSWORD, "");
                        EnvironmentVariable.setUserName("");
                        EnvironmentVariable.setPassword("");
                        try {
                            Intent intent = new Intent(mContext, Class.forName("com.efounder.activity.Login_withTitle"));
                            intent.putExtra("logOut", true);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            ((Activity) mContext).finish();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                })
                .create()
                .show();
    }


    /**
     * 登陆过期以及用户不存在提示
     */
//    private void showLogOutAlert(String msg) {
//        new AlertDialog.Builder(mContext)
//                .setTitle("提示")
//                .setMessage(msg)
//                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        EnvironmentVariable.setProperty("tc_ethAddress", "");
//                        EnvironmentVariable.setProperty("tc_ethPublicKey", "");
//                        EventBus.getDefault().post(new LogoutEvent());
//                    }
//                }).setCancelable(false)
//                .create().show();
//    }
}
